package com.b2b.controller;


import com.alibaba.fastjson.JSONObject;
import com.b2b.model.CompanyInfoDto;
import com.b2b.model.PersonalAuthenticationDto;
import com.b2b.model.common.ResponseBean;
import com.b2b.model.CompanyAuthenticationDto;
import com.b2b.model.entity.company.CompanyInfo;
import com.b2b.service.CompanyAuthenticationService;
import com.b2b.service.CompanyInfoService;
import com.b2b.service.PersonalAuthenticationService;
import com.b2b.util.common.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.*;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/authentication")
public class AuthenticationController {

    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    //API密钥secretId
    @Value("${spring.qcloud.secretId}")
    private String secretId;
    //API密钥secretKey
    @Value("${spring.qcloud.secretKey}")
    private String secretKey;
    //存储桶所属地域
    @Value("${spring.qcloud.region}")
    private String region;
    //存储桶空间名称
    @Value("${spring.qcloud.bucketName}")
    private String bucketName;
    //存储桶访问域名
    @Value("${spring.qcloud.url}")
    private String url;
    //上传文件前缀路径(eg:/images/)
    @Value("${spring.qcloud.prefix}")
    private String prefix;

    @Autowired
    CompanyAuthenticationService companyAuthenticationService;

    @Autowired
    PersonalAuthenticationService personalAuthenticationService;

    @Autowired
    CompanyInfoService companyInfoService;

    @PostMapping("/company")
    public ResponseBean companyAuthentication(@RequestBody Map<String, Object> map) throws TencentCloudSDKException {

        if (map.containsKey("companyId") && !map.get("companyId").equals("") && map.containsKey("imgUrl") && !map.get("imgUrl").equals("")) {
            Integer companyId = Integer.parseInt(map.get("companyId").toString());

            if (companyInfoService.selectByPrimaryKey(companyId).getState().equals("0")) {
                try {
                    // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
                    // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
                    Credential cred = new Credential(secretId, secretKey);
                    // 实例化一个http选项，可选的，没有特殊需求可以跳过
                    HttpProfile httpProfile = new HttpProfile();
                    httpProfile.setEndpoint("ocr.tencentcloudapi.com");
                    // 实例化一个client选项，可选的，没有特殊需求可以跳过
                    ClientProfile clientProfile = new ClientProfile();
                    clientProfile.setHttpProfile(httpProfile);
                    // 实例化要请求产品的client对象,clientProfile是可选的
                    OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
                    // 实例化一个请求对象,每个接口都会对应一个request对象
                    String imgUrl = map.get("imgUrl").toString();
                    VerifyBasicBizLicenseRequest req = new VerifyBasicBizLicenseRequest();
                    req.setImageUrl(imgUrl);
                    req.setImageConfig("{\"RegNum\":true,\"Name\":true,\"Address\":true}");
                    // 返回的resp是一个VerifyBasicBizLicenseResponse的实例，与请求对象对应
                    VerifyBasicBizLicenseResponse resp = client.VerifyBasicBizLicense(req);
                    // 输出json格式的字符串回包
                    CompanyAuthenticationDto companyAuthenticationDto = new CompanyAuthenticationDto();
                    companyAuthenticationDto.setAuthenticationTime(TimeUtil.getDateTime());
                    companyAuthenticationDto.setCompanyName(resp.getVerifyEntname());
                    companyAuthenticationDto.setBusinessLicense(resp.getCreditCode());
                    companyAuthenticationDto.setCorporationName(resp.getFrname());
                    companyAuthenticationDto.setImgUrl(imgUrl);
                    companyAuthenticationDto.setBusinessLicenseAddress(resp.getVerifyDom());
                    if(!resp.getOpto().equals("")) {
                        companyAuthenticationDto.setBusinessYears(TimeUtil.strToDate(resp.getOpto()));
                    }
                    companyAuthenticationDto.setNatureOfBusiness(resp.getZsopscope());
                    companyAuthenticationDto.setCompanyId(Integer.parseInt(map.get("companyId").toString()));
//                    if (!resp.getRegNumResult().getRegNum().equals("0") | !resp.getRegNumResult().getAddress().equals("0")
//                            | !resp.getRegNumResult().getName().equals("0") | resp.getEntstatus().equals("注销")) {
                    if (!resp.getRegNumResult().getRegNum().equals("0") | !resp.getRegNumResult().getAddress().equals("0")
                            | !resp.getRegNumResult().getName().equals("0")) {
                        companyAuthenticationDto.setState('0');
                        companyAuthenticationService.insert(companyAuthenticationDto);
                        return new ResponseBean(HttpStatus.OK.value(), "信息不一致或执照已被注销", null);
                    }
                    companyAuthenticationDto.setState('1');
                    companyAuthenticationService.insert(companyAuthenticationDto);
                    CompanyInfo companyInfo = new CompanyInfo();
                    companyInfo.setCompanyId(companyId);
                    companyInfo.setCompanyName(companyAuthenticationDto.getCompanyName());
                    companyInfo.setBusinessLicense(companyAuthenticationDto.getBusinessLicense());
                    companyInfo.setCorporationName(companyAuthenticationDto.getCorporationName());
                    companyInfo.setRegisteredArea(companyAuthenticationDto.getBusinessLicenseAddress());
                    companyInfo.setState('1');
                    companyInfoService.updateByPrimaryKeySelective(companyInfo);
                    return new ResponseBean(HttpStatus.OK.value(), "认证已通过", null);
                } catch (TencentCloudSDKException | ParseException e) {
                    System.out.println(e);
                    return new ResponseBean(HttpStatus.FORBIDDEN.value(), "未知错误", null);
                }
            } else {
                return new ResponseBean(HttpStatus.FORBIDDEN.value(), "已通过认证,请勿重复提交", null);
            }
        } else {
            return new ResponseBean(HttpStatus.FORBIDDEN.value(), "信息不完整", null);
        }
    }

    @PostMapping("/personal")
    public ResponseBean IDAuthentication(@RequestBody Map<String, Object> map) throws TencentCloudSDKException {

        if(!map.containsKey("frontViewUrl")) {

            try {
                // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
                // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
                Credential cred = new Credential("SecretId", "SecretKey");
                // 实例化一个http选项，可选的，没有特殊需求可以跳过
                HttpProfile httpProfile = new HttpProfile();
                httpProfile.setEndpoint("ocr.tencentcloudapi.com");
                // 实例化一个client选项，可选的，没有特殊需求可以跳过
                ClientProfile clientProfile = new ClientProfile();
                clientProfile.setHttpProfile(httpProfile);
                // 实例化要请求产品的client对象,clientProfile是可选的
                OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
                // 实例化一个请求对象,每个接口都会对应一个request对象
                IDCardOCRRequest req = new IDCardOCRRequest();
                req.setImageUrl(map.get("frontViewUrl").toString());
                req.setCardSide("FRONT");
                req.setConfig("{\"TempIdWarn\":true, \"Quality\":true, \"BorderCheckWarn\":true}");
                // 返回的resp是一个IDCardOCRResponse的实例，与请求对象对应
                IDCardOCRResponse resp = client.IDCardOCR(req);

                PersonalAuthenticationDto personalAuthenticationDto = new PersonalAuthenticationDto();
                personalAuthenticationDto.setName(resp.getName());
                personalAuthenticationDto.setIDNumber(resp.getIdNum());

                Map<String, Object> advancedInfo = JSONObject.parseObject(resp.getAdvancedInfo());
                if (advancedInfo != null) {
                    personalAuthenticationDto.setState('0');
                    personalAuthenticationService.insert(personalAuthenticationDto);
                    if (Integer.parseInt(advancedInfo.get("Quality").toString()) < 50)
                        return new ResponseBean(HttpStatus.OK.value(), "上传的照片不清晰", null);
                    if (Integer.parseInt(advancedInfo.get("BorderCodeValue").toString()) < 50)
                        return new ResponseBean(HttpStatus.OK.value(), "请上传完整的身份证照片", null);
                    return new ResponseBean(HttpStatus.OK.value(), "检测到临时身份证", null);
                }
                personalAuthenticationDto.setState('1');
            } catch (TencentCloudSDKException e) {
                System.out.println(e.toString());
                return new ResponseBean(HttpStatus.OK.value(), "未知错误", null);
            }
            return new ResponseBean(HttpStatus.OK.value(), "认证已通过", null);
        }else {
            return new ResponseBean(HttpStatus.FORBIDDEN.value(), "请上传完整身份证正面照", null);
        }
    }


    @GetMapping("/getCompany")
    public ResponseBean getCompany(@RequestParam Map<String, Object> map){
        int page = 1, rows = 10;
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());

        PageHelper.startPage(page, rows);

        CompanyAuthenticationDto companyAuthenticationDto = new CompanyAuthenticationDto();
        companyAuthenticationDto.setState(map.get("state").toString().charAt(0));
        List<CompanyAuthenticationDto> companyAuthenticationDtoList = companyAuthenticationService.select(companyAuthenticationDto);

        PageInfo<CompanyAuthenticationDto> selectPage = new PageInfo<>(companyAuthenticationDtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("authenticationList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);

    }

    @GetMapping("/getPersonal")
    public ResponseBean getPersonal(@RequestParam Map<String, Object> map){
        int page = 1, rows = 10;
        char state = '0';
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());
        if(map.containsKey("state"))
            state = map.get("state").toString().charAt(0);

        PageHelper.startPage(page, rows);
        PersonalAuthenticationDto personalAuthenticationDto = new PersonalAuthenticationDto();
        personalAuthenticationDto.setState(state);
        List<PersonalAuthenticationDto> personalAuthenticationDtoList = personalAuthenticationService.select(personalAuthenticationDto);
        PageInfo<PersonalAuthenticationDto> selectPage = new PageInfo<>(personalAuthenticationDtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("authenticationList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);

    }

}
